#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
using namespace std;

std::timed_mutex mtx;

void foo(int &num, int id)
{
    // 愿意等 100 ms；抢不到就放弃
    if (mtx.try_lock_for(std::chrono::milliseconds(100)))
    {
        cout << "[Thread " << id << "] 抢到锁，开始干活\n";
        // 时间短可以抢占
        // std::this_thread::sleep_for(std::chrono::milliseconds(30));
        // 时间太长导致无法抢占，退出
        std::this_thread::sleep_for(std::chrono::milliseconds(110));
        ++num;
        mtx.unlock();
    }
    else
    {
        cout << "[Thread " << id << "] 等了100 ms 也没抢到，溜了\n";
    }
}

int main()
{
    int num = 1;
    thread t1(foo, std::ref(num), 1);
    thread t2(foo, std::ref(num), 2);

    t1.join();
    t2.join();

    cout << "final num = " << num << '\n';
    return 0;
}